import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { RootState } from '../store';
import { login as userLogin, LoginParams, getUserInfo } from '../../api/user';

const namespace = 'user';
const TOKEN_NAME = 'zy-swimming-pool';

const initialState = {
  token: localStorage.getItem(TOKEN_NAME) || '', // 默认token不走权限
  userInfo: {},
  error: null,
};

// login
export const login = createAsyncThunk(`${namespace}/login`, async (userInfo: LoginParams) => {
  const res = await userLogin(userInfo);
  console.log(res);
  if (res.code === 200) {
    return res.data;
  }
  throw new Error(res.msg);
});
// getUserInfo
export const getUser = createAsyncThunk(`${namespace}/getUserInfo`, async () => {
  const res = await getUserInfo();
  return res;
});

const userSlice = createSlice({
  name: namespace,
  initialState,
  reducers: {
    logout: (state) => {
      localStorage.removeItem(TOKEN_NAME);
      state.token = '';
      state.userInfo = {};
    },
    remove: (state) => {
      state.token = '';
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(login.fulfilled, (state, action) => {
        localStorage.setItem(TOKEN_NAME, action.payload);

        state.token = action.payload;
      })
      .addCase(login.rejected, (state, action) => {
        console.log(action.error);
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        throw action.error;
      })
      .addCase(getUser.fulfilled, (state, action) => {
        state.userInfo = action.payload.data;
      });
  },
});

export const selectUserBase = (state: RootState) => state.user;

export const { logout, remove } = userSlice.actions;

export default userSlice.reducer;
